<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="addRole">添加角色</el-button>
      </div>
      <!-- table组件 -->
      <el-table :data="roleList">
        <!-- 列 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" type="text" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <template #default="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" type="text" />
            <span v-else>{{ row.state === 1 ? '已启用' : row.state === 0 ? "未启用" : "无" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="comfirmEdit(row)">确定</el-button>
              <el-button size="mini" type="text" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="editRole(row)">编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="delRole(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 分页组件 -->
        <el-pagination
          layout="prev, pager, next"
          :page-size="params.pagesize"
          :total="params.total"
          :current-page="params.page"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <!-- 新增角色的弹窗 -->
      <el-dialog :visible.sync="showDialog" title="新增角色" @close="close">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" size="mini" />
          </el-form-item>
          <el-form-item label="启用" prop="state">
            <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="roleForm.description" :rows="3" size="mini" />
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col>
                <el-button type="primary" size="mini" @click="submit">确定</el-button>
                <el-button size="mini" @click="close">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 分配权限弹窗 -->
      <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
        <!-- 放置权限数据 -->
        <el-tree
          ref="permTree"
          :data="permissionData"
          :props="{ label: 'name' }"
          show-checkbox
          default-expand-all
          node-key="id"
          :default-checked-keys="permIds"
        />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
            <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>

    </div>

  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { addRoleAPI, assignPerm, deleteRole, getRoleDetail, getRoleListAPI, updateRole } from '@/api/role'
import { totree } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      roleList: [],
      params: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      showDialog: false,
      roleForm: {
        name: '',
        state: 0, // 默认未 1启用 关闭 0 打开1
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null, // 当前角色id
      permIds: [] // 权限id数组
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      const res = await getRoleListAPI(this.params)
      this.roleList = res.rows
      this.params.total = res.total
      // 给每条数据添加一个isEdit属性，用于标识是否处于编辑状态（新属性不具备响应式，不能控制显示隐藏）
      // $set方法用于设置响应式属性
      // this.$set(目标对象, '属性名', 初始值)
      this.roleList.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    handleCurrentChange(newPage) {
      this.params.page = newPage
      this.getRoleList()
    },
    // 添加角色
    addRole() {
      this.showDialog = true
    },
    async submit() {
      this.$refs.roleForm.validate()
      await addRoleAPI(this.roleForm)
      this.$message.success('添加角色成功')
      this.showDialog = false
      this.getRoleList()
      this.close()
    },
    close() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
    },
    // 编辑角色
    editRole(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 确认编辑
    async comfirmEdit(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRole({ id: row.id, ...row.editRow })
        this.$message.success('编辑角色成功')
        // 更新显示数据  退出编辑状态
        // Object.assign(target, ...sources)
        Object.assign(row, {
          isEdit: false,
          ...row.editRow
        })
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    async delRole(id) {
      await deleteRole(id)
      this.$message.success('删除角色成功')
      // 删除的如果是最后一个
      if (this.roleList.length === 1) {
        this.params.page--
      }
      this.getRoleList()
    },
    // 权限列表
    async btnPermission(id) {
      this.currentRoleId = id
      // 1. 获取权限列表
      this.permissionData = totree(await getPermissionList(), 0)
      // 2. 获取当前角色的权限id数组
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds

      // last. 显示弹层  原因：加载数据异步，希望弹层显示时，数据已经加载完成
      this.showPermissionDialog = true
    },
    // 确认分配权限
    async btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>

<style scoped>
.role-operate {
  padding: 10px;
}
</style>
